package com.servlet.mysert;

import com.domain.Mysert;
import com.service.MysertService;
import com.service.impl.MysertServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/mysertAddServlet")
public class MysertAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求过来的参数编码格式为utf8
        request.setCharacterEncoding("utf-8");
        // 创建实体类
        Mysert mysert = new Mysert();
        try {
            // 将获取的请求参数map集合封装到实体类中
            BeanUtils.populate(mysert,request.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        // 创建service对象
        MysertService service = new MysertServiceImpl();

        // 当service保存成功后反会为true时
        if(service.save(mysert)) {
            // 响应数据
            response.getWriter().write("{\"status\":\"0\",\"message\":\"ok\"}");
        }else {
            response.getWriter().write("{\"status\":\"1\",\"message\":\"error\"}");
        }


    }
}
